package com.wdd.myplatform.controller.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

/**
 * @author wdd 2022/4/25
 */
@Slf4j
public abstract class AbstractMqttCallBackStrategy implements MqttCallback {
    private String clientId;

    private MqttConnectOptions connectOptions;

    private String topic;

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public MqttConnectOptions getConnectOptions() {
        return connectOptions;
    }

    public void setConnectOptions(MqttConnectOptions connectOptions) {
        this.connectOptions = connectOptions;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    /**
     * 失去连接操作,进行重连
     *
     * @param throwable 异常
     */
    @Override
    public void connectionLost(Throwable throwable) {
        try {
            if (null != clientId) {
                MqttClient mqttClient = MqttClientManager.getMqttClientById(clientId);
                if (null != connectOptions) {
                    mqttClient.connect(connectOptions);
                } else {
                    mqttClient.connect();
                }
                mqttClient.subscribe(topic);
            }
        } catch (Exception e) {
            log.error("{} reconnect failed!", e);
        }
    }

    /**
     * 接收订阅消息
     *
     * @param s           主题
     * @param mqttMessage 接收消息
     * @throws Exception 异常
     */
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        String content = new String(mqttMessage.getPayload());
        log.info("Receive topic[{}],message={}", s, content);
        handleReceiveMessage(s, content);
    }

    /**
     * 消息发送成功
     *
     * @param iMqttDeliveryToken toke
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    }


    /**
     * 处理接收的消息
     *
     * @param topic   主题
     * @param message 消息内容
     */
    protected abstract void handleReceiveMessage(String topic, String message);
}
